<template>
  <div class="user-spaces-view max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- 顶部区域 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-3xl font-bold text-gray-900">我的工作空间</h1>
    </div>
    <!--space列表-->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <SpaceCard v-for="(spaceVo, index) in spaceVos"
                 :key="index"
                 :space-vo="spaceVo">
      </SpaceCard>
      <!-- 创建新项目卡片 -->
      <div
          @click="openCreateSpaceModal"
          class="bg-white rounded-lg shadow-sm border-2 border-dashed border-gray-300 p-6 flex flex-col items-center justify-center text-center hover:border-indigo-500 transition-colors duration-300 cursor-pointer group h-64">
        <div
            class="h-12 w-12 rounded-full bg-indigo-100 flex items-center justify-center mb-3 group-hover:bg-indigo-200 transition-colors duration-200">
          <svg t="1748517955795"
               class="icon w-6 h-6 text-indigo-600 group-hover:text-indigo-700 transition-colors duration-200"
               viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9050"
               fill="currentColor">
            <path
                d="M925.696 384q19.456 0 37.376 7.68t30.72 20.48 20.48 30.72 7.68 37.376q0 20.48-7.68 37.888t-20.48 30.208-30.72 20.48-37.376 7.68l-287.744 0 0 287.744q0 20.48-7.68 37.888t-20.48 30.208-30.72 20.48-37.376 7.68q-20.48 0-37.888-7.68t-30.208-20.48-20.48-30.208-7.68-37.888l0-287.744-287.744 0q-20.48 0-37.888-7.68t-30.208-20.48-20.48-30.208-7.68-37.888q0-19.456 7.68-37.376t20.48-30.72 30.208-20.48 37.888-7.68l287.744 0 0-287.744q0-19.456 7.68-37.376t20.48-30.72 30.208-20.48 37.888-7.68q39.936 0 68.096 28.16t28.16 68.096l0 287.744 287.744 0z"
                p-id="9051"></path>
          </svg>
        </div>
        <h3 class="text-lg font-medium text-gray-900 group-hover:text-indigo-600 transition-colors duration-200">
          创建新空间</h3>
        <p class="mt-1 text-sm text-gray-500">开始一个新的素材协作空间</p>
      </div>
    </div>

    <!-- 创建新空间弹窗 -->
    <Transition name="fade">
      <div v-if="isModalOpen"
           class="fixed inset-0 bg-opacity-60 flex items-center justify-center z-50 transition-opacity">
        <div class="bg-white rounded-xl shadow-2xl w-full max-w-lg mx-4" ref="modalContentRef">
          <div class="p-6 pb-2 border-b border-gray-200">
            <h2 class="text-2xl font-bold text-gray-800">创建新的工作空间</h2>
            <p class="text-sm text-gray-500 mt-1">设置您的空间，开始协作</p>
          </div>
          <div class="p-6">
            <form @submit.prevent="handleCreateSpace">
              <div class="space-y-6">
                <div>
                  <label for="spaceName" class="block text-sm font-medium text-gray-700 mb-1">空间名称</label>
                  <input type="text" id="spaceName" v-model="form.name"
                         class="w-full h-12 px-4 border border-gray-300 rounded-lg transition duration-200 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                         placeholder="例如：市场营销团队">
                </div>
                <div>
                  <label for="spaceDesc" class="block text-sm font-medium text-gray-700 mb-1">空间简介</label>
                  <textarea id="spaceDesc" v-model="form.description" rows="2" maxlength="50"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg transition duration-200 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 resize-none"
                            placeholder="简单介绍这个空间的用途（不超过50字）"></textarea>
                  <p class="text-xs text-gray-400 mt-1 text-right">{{ form.description.length }}/50</p>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">空间版本</label>
                  <CustomSelect v-model="form.level" :options="spaceLevelOptions"
                                placeholder="选择一个空间版本"/>
                </div>
              </div>
            </form>
          </div>
          <div class="px-6 py-4 bg-gray-50 rounded-b-xl flex justify-end space-x-3">
            <button @click="closeCreateSpaceModal" type="button"
                    class="px-5 py-2.5 rounded-lg bg-gray-200 text-gray-800 font-semibold hover:bg-gray-300">
              取消
            </button>
            <button @click="handleCreateSpace" type="submit"
                    :disabled="isCreating"
                    class="px-5 py-2.5 rounded-lg bg-indigo-600 text-white font-semibold hover:bg-indigo-700 flex items-center justify-center w-[108px]"
                    :class="{'bg-indigo-400 cursor-not-allowed': isCreating}">
              <svg v-if="isCreating" class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg"
                   fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span v-else>创建空间</span>
            </button>
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import SpaceCard from "@/pages/SpacePage/components/SpaceCard.vue";
import CustomSelect from "@/components/CustomSelect.vue";
import {useRouter} from "vue-router";
import {onMounted, ref, reactive} from "vue";
import type {AbbreviationSpaceVo, CreateSpaceRequest} from "@/api/space-service";
import {message} from "@/plugins/message";
import {createSpaceRequestByPost, getAbbreviationSpaceVoRequestByGet} from "@/api/space-service";

const router = useRouter()
const spaceVos = ref<AbbreviationSpaceVo[]>([])

// --- Modal State & Logic ---
const isModalOpen = ref(false);
const modalContentRef = ref(null);
const isCreating = ref(false);

const form = reactive({
  name: '',
  description: '',
  level: 0, // 0: 普通版, 2: 专业版, 1: 旗舰版
});

const spaceLevelOptions = ref([
  {value: 0, label: '普通版'},
  {value: 1, label: '旗舰版'},
  {value: 2, label: '专业版'},
]);

onMounted(() => {
  getAbbreviationSpaceVos()
})

const getAbbreviationSpaceVos = async () => {
  try {
    const res = await getAbbreviationSpaceVoRequestByGet()
    if (res.code != 200) {
      message.error("请求失败", res.description)
    }
    spaceVos.value = res.data
  } catch (e) {
    message.error("请求异常", "网络错误")
  }
}


const openCreateSpaceModal = () => {
  isModalOpen.value = true;
};

const closeCreateSpaceModal = () => {
  isModalOpen.value = false;
  // Reset form
  form.name = '';
  form.description = '';
  form.level = 0;
};

const handleCreateSpace = async () => {
  if (!form.name) {
    message.error("创建失败", "空间名字为空")
    return
  }

  if (!form.description) {
    message.error("创建失败", "空间简介为空")
    return
  }

  isCreating.value = true;

  const createSpaceRequest = {
    spaceName: form.name,
    spaceLevel: form.level,
    profile: form.description
  } as CreateSpaceRequest

  try {
    const res = await createSpaceRequestByPost(createSpaceRequest)
    if (res.code === 200) {
      message.success("创建成功", `${form.name}已创建`);
      await getAbbreviationSpaceVos();
    } else {
      message.error("创建失败", res.description);
    }
  } catch (e) {
    message.error("创建失败", "网络请求失败，请稍后重试。");
  } finally {
    isCreating.value = false;
    closeCreateSpaceModal();
  }
};

</script>

<style scoped>
</style>